package center

import (
	"fmt"
)

type Packet struct {
	cmd_code int16
	data_len int32
	data     []byte
}

func newPacket() *Packet {
	return new(Packet)
}

var _handlers = map[int16]func(*Packet, *Conninfo){
	0x0001: p0001,
	0x0002: p0002,
	0x0011: p0011,
	0x0013: p0013,
	0x0014: p0014,
	0x0015: p0015,
	0x0016: p0016,
	0x0031: p0031,
	0x0042: p0042,
	0x0061: p0061,
}

func (p *Packet) handle(coni *Conninfo) {
	if p.unseal(coni) == false {
		return
	}
	hanndlePacket(p, coni)
}

func hanndlePacket(p *Packet, coni *Conninfo) {
	//if p.data_len == 0 {
	//	fmt.Println("empty data")
	//	return
	//}
	fmt.Println(p.cmd_code, p.data_len, p.data)

	if h, ok := _handlers[p.cmd_code]; !ok {
		fmt.Println("invalid cmd_code(%d)", p.cmd_code)
		return
	} else {
		if h == nil {
			fmt.Println("null handler for cmd_code(%d)", p.cmd_code)
			return
		}
		fmt.Println("received data:", p.cmd_code)
		h(p, coni)
	}
}

func (p *Packet) seal() []byte {
	p.data_len = int32(len(p.data))
	output := make([]byte, 0)
	output = append(output, int16ToByte(p.cmd_code)...)
	output = append(output, int32ToByte(p.data_len)...)
	output = append(output, p.data...)
	return output
}

func (p *Packet) unseal(coni *Conninfo) bool {
	p.cmd_code = byteToInt16(coni.data[0:2])
	p.data_len = byteToInt32(coni.data[2:6])
	if p.data_len+6 != int32(coni.data_len) {
		fmt.Println("datalen error!")
		return false
	}
	p.data = coni.data[6:(6 + p.data_len)]
	return true
}

func (p *Packet) send(coni *Conninfo) {
	data := p.seal()
	fmt.Println("send:", data, "dataLen:", len(data))
	coni.Write(data)
}
